package reference;

import java.lang.ref.PhantomReference;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @program JavaBase
 * @description: 虚引用 - 直接内存堆外内存管理nio、netty
 *  虚引用对象get获取不到值
 *  当某一个虚引用对象被回收时，会将其填到队列里
 * @author: zhanglu
 * @create: 2020-12-13 17:02:00
 */
public class Re04_PhantomRefernce {

    private static final List<Object> list = new LinkedList<>();
    private static final ReferenceQueue<RefernceFinalize> queue = new ReferenceQueue<>();

    public static void main(String[] args) {
        PhantomReference<RefernceFinalize> phantomReference = new PhantomReference<>(new RefernceFinalize(), queue);
        new Thread(() -> {
            while (true){
                list.add(new byte[1024 * 1024]);
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(phantomReference.get());
            }
        }).start();

        new Thread(() -> {
            while (true){
                Reference<? extends RefernceFinalize> poll = queue.poll();
                if(poll != null){
                    RefernceFinalize refernceFinalize = poll.get();
                    System.out.println("--- 虚引用对象被jvm回收了 ---" + refernceFinalize);
                }
            }
        }).start();

        while (true){}
    }

}
